package com.hundsun.documentripper.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hundsun.documentripper.domain.dto.DocumentVersionView;
import com.hundsun.documentripper.domain.pojo.Document;
import com.hundsun.documentripper.domain.pojo.DocumentVersion;
import com.hundsun.documentripper.domain.pojo.File;
import com.hundsun.documentripper.domain.query.DocumentVersionQuery;
import com.hundsun.documentripper.mapper.DocumentMapper;
import com.hundsun.documentripper.mapper.DocumentVersionMapper;
import com.hundsun.documentripper.service.DocumentService;
import com.hundsun.documentripper.service.FileService;

/**
 * Note：
 *
 * @author ：mengjw
 * @description：文档接口实现
 * @date ：Created in 2021/1/27
 */
@Service
public class DocumentServiceImpl implements DocumentService {

    @Autowired
    private DocumentMapper documentMapper;
    @Autowired
    private DocumentVersionMapper documentVersionMapper;
    @Autowired
    private FileService fileService;

    @Override
    public void insertDocumentFromFile(File file) {
        // 插入文档数据
        Document document = Document.builder()
                .uuid(file.getDocumentUuid())
                .productUuid(file.getProductUuid())
                .startProductVersionUuid(file.getProductVersionUuid())
                .versionCount(0)
                .isFolder(file.getIsFolder())
                .createUser(file.getCreateUser())
                .build();
        documentMapper.insert(document);
        // 插入初始文档版本数据
        DocumentVersion documentVersion = DocumentVersion.builder()
                .documentUuid(file.getDocumentUuid())
                .documentVersion(0)
                .productVersionUuid(file.getProductVersionUuid())
                .fileUuid(file.getUuid())
                .createUser(file.getCreateUser())
                .build();
        documentVersionMapper.insert(documentVersion);
    }

    @Override
    public void updateDocument(Document document) {
        documentMapper.updateById(document);
    }

    @Override
    public Document getDocumentById(String uuid) {
        return documentMapper.selectById(uuid);
    }

    @Override
    public IPage<DocumentVersionView> getDocumentVersionListByPage(DocumentVersionQuery documentVersionQuery) {
        QueryWrapper<DocumentVersionView> wrapper = new QueryWrapper<>();
        wrapper.eq(!StringUtils.isEmpty(documentVersionQuery.getDocumentUuid()),
                "a.document_uuid", documentVersionQuery.getDocumentUuid());
        wrapper.eq(!StringUtils.isEmpty(documentVersionQuery.getProductVersionUuid()),
                "a.product_version_uuid", documentVersionQuery.getProductVersionUuid());
        wrapper.eq(!StringUtils.isEmpty(documentVersionQuery.getUserUuid()),
                "a.create_user", documentVersionQuery.getUserUuid());
        wrapper.like(!StringUtils.isEmpty(documentVersionQuery.getFileName()),
                "IFNULL(f.name, h.name)", documentVersionQuery.getFileName());
        wrapper.orderByDesc("create_time");
        return documentVersionMapper.selectDocumentVersion(
                new Page<DocumentVersionView>(documentVersionQuery.getCurrent(), documentVersionQuery.getSize()), wrapper);
    }

    @Override
    public List<DocumentVersionView> getDocumentVersionList(DocumentVersionQuery documentVersionQuery) {
        QueryWrapper<DocumentVersionView> wrapper = new QueryWrapper<>();
        wrapper.eq(!StringUtils.isEmpty(documentVersionQuery.getDocumentUuid()),
                "a.document_uuid", documentVersionQuery.getDocumentUuid());
        wrapper.eq(!StringUtils.isEmpty(documentVersionQuery.getProductVersionUuid()),
                "a.product_version_uuid", documentVersionQuery.getProductVersionUuid());
        wrapper.eq(!StringUtils.isEmpty(documentVersionQuery.getUserUuid()),
                "a.create_user", documentVersionQuery.getUserUuid());
        wrapper.like(!StringUtils.isEmpty(documentVersionQuery.getFileName()),
                "IFNULL(f.name, h.name)", documentVersionQuery.getFileName());
        wrapper.orderByDesc("create_time");
        return documentVersionMapper.selectAllDocumentVersion(wrapper);
    }

    @Override
    public void insertDocumentVersion(DocumentVersion documentVersion) {
        documentVersionMapper.insert(documentVersion);
    }

    @Override
    public List<DocumentVersion> getLastDocumentVersionByProductVersion(String productVersionUuid) {
        return documentVersionMapper.getLastDocumentVersionByProductVersion(productVersionUuid);
    }

    @Override
    public void updateNewDocumentVersion(DocumentVersion documentVersion) {
        QueryWrapper<DocumentVersion> wrapper = new QueryWrapper<>();
        wrapper.eq("document_uuid", documentVersion.getDocumentUuid());
        wrapper.eq("document_version", 0);
        wrapper.eq("product_version_uuid", documentVersion.getProductVersionUuid());
        documentVersionMapper.update(documentVersion, wrapper);
    }

    @Override
    public void deleteDocumentVersionByFile(String fileUuid) {
        QueryWrapper<DocumentVersion> wrapper = new QueryWrapper<>();
        wrapper.eq("file_uuid", fileUuid);
        DocumentVersion documentVersion = documentVersionMapper.selectOne(wrapper);
        documentVersionMapper.delete(wrapper);
        // 如果删除的文档没有其他版本了，删除文档信息
        removeEmptyDocument(documentVersion.getDocumentUuid());
    }

    @Override
    public void deleteDocumentVersionsByProductVersion(String productVersionUuid) {
        QueryWrapper<DocumentVersion> wrapper = new QueryWrapper<>();
        wrapper.eq("product_version_uuid", productVersionUuid);
        List<DocumentVersion> documentVersionList = documentVersionMapper.selectList(wrapper);
        documentVersionMapper.delete(wrapper);
        // 如果删除的文档没有其他版本了，删除文档信息
        for (DocumentVersion documentVersion : documentVersionList) {
            removeEmptyDocument(documentVersion.getDocumentUuid());
        }
    }

    @Override
    public void deleteDocumentVersionByProductVersion(String productVersionUuid, String uuid) {
        QueryWrapper<DocumentVersion> wrapper = new QueryWrapper<>();
        wrapper.eq("product_version_uuid", productVersionUuid);
        wrapper.eq("document_uuid", uuid);
        List<DocumentVersion> list = documentVersionMapper.selectList(wrapper);
        // 删除相关的文件及其文档版本
        for (DocumentVersion documentVersion : list) {
            fileService.deleteFile(documentVersion.getFileUuid());
        }
    }

    /**
     * 如果文档没有其他版本了，删除文档信息
     *
     * @param documentUuid
     */
    private void removeEmptyDocument(String documentUuid) {
        // 查询当前文档剩余的其他版本
        QueryWrapper<DocumentVersion> wrapper = new QueryWrapper<>();
        wrapper.eq("document_uuid", documentUuid);
        List<DocumentVersion> documentVersionList = documentVersionMapper.selectList(wrapper);
        if (documentVersionList.isEmpty()) {
            // 如果当前文档没有其他版本了，删除文档信息
            documentMapper.deleteById(documentUuid);
        }
    }

}